#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import configparser
import GenCustomRules
import PropertiesReader
import ClassPathFileReader
import GameInfoReader

#
android_tools_dir = ""
app_copy_path = ""

#依赖库路径
reflib_dir_list = []

#app目录下要创建的目录
output_dir_list = []

#ant.properties、key文件的源和目标
cfgfile_path_dict = []

#custom_rules的源和目标
customrulesfile_path_dict = []

	
#def : 初始化路径相关信息
def initConfig():
	#基本配置信息
	projectconfigRd = GameInfoReader.GameInfoReader("./userconfig/gameinfo.conf")	
	global android_tools_dir
	global app_copy_path
	android_tools_dir = os.path.abspath( projectconfigRd.getOneProjectInfo("android_tools_dir") )
	app_copy_path = os.path.abspath( projectconfigRd.getOneProjectInfo("app_copy_path") )
	if( False == os.path.exists(android_tools_dir) ):
		raise Exception(android_tools_dir + "目录不存在，请检查!")
	
	#output_dir_list
	output_dir_list.append(app_copy_path + r"/key")
	output_dir_list.append(app_copy_path + r"/output")
	output_dir_list.append(app_copy_path + r"/compile")

	#cfgfile_path_dict
	cfgfile_path_dict.append(("./userconfig/ant.properties",app_copy_path + "/ant.properties"))
	cfgfile_path_dict.append(("./key/release.keystore",app_copy_path + "/key/release.keystore"))
	
	#customrulesfile_path_dict(用于指定custom_rules.xml的源和目标)
	classpathreader = ClassPathFileReader.ClassPathFileReader()
	refprolist = PropertiesReader.getDupRemoveLibProject(app_copy_path,"project.properties")
	refprolist.append(app_copy_path)
	for projectpath in refprolist:
		projectname = classpathreader.getProjectName(projectpath,".project")
		srcpath = "./custom_rules/" + projectname + "_custom_rules.xml"
		despath = projectpath + "/custom_rules.xml"
		customrulesfile_path_dict.append((srcpath,despath))
	
	#reflib_dir_list（用于指定哪些目录需要生成build.xml）
	global reflib_dir_list
	reflib_dir_list = PropertiesReader.getDupRemoveLibProject(app_copy_path,"project.properties")
	
	
#def : 初始化compile、output、key目录
def createOneDir(dirname):
	if(False == os.path.exists(dirname)):
		os.makedirs(dirname)
	
def createOutputDir():
	#先删除output目录，保证输出目录下文件是最新的
	outputdir = app_copy_path + r"/output"
	if(os.path.exists(outputdir)):
		shutil.rmtree(outputdir,True)

	print("begin to create directory.")
	for dirname in output_dir_list:
		createOneDir(dirname)
	print("finish create directory.")

#def : 生成所有工程的build.xml
def initOneBuildXML(dirname):
	if(False == os.path.exists(dirname)):
		raise Exception(dirname + " 目录不存在，请检查")
		
	#删除旧build.xml文件
	buildfilename = dirname + "/" + "build.xml";
	if(os.path.exists(buildfilename)):
		print(buildfilename,"has exist,delete it!")
		os.remove(buildfilename)

	#执行"android update project -p"命令
	cmdname = android_tools_dir + "/android update project -p " + dirname
	os.system(cmdname)

def initAllBuildXML():
	print("begin to update build.xml")
	initOneBuildXML(app_copy_path)
	for dirname in reflib_dir_list:
		initOneBuildXML(dirname)
	print("finish update build.xml")
		
#def : copy需要的custom_rules.xml、ant.properties、local.properties、key文件
def copyListFile(filelist):
	for customruleobj in filelist:
		if(os.path.exists(customruleobj[0])):
			if(os.path.exists(customruleobj[1])):
				print(customruleobj[1] + " is exist,delete and copy!")
				os.remove(customruleobj[1])
			shutil.copyfile(customruleobj[0],customruleobj[1])
		else:
			raise Exception(customruleobj[0] + " 文件不存在，请检查")

def copyCustomRulesFiles():
	print("begin to copy custom_rules.xml")
	copyListFile(customrulesfile_path_dict)
	print("finish copy custom_rules.xml")

def copyConfigFiles():
	print("begin to copy config file")
	copyListFile(cfgfile_path_dict)
	print("finish copy config file")
	
#def : 去目标工程目录下执行ant deploy
def antCreateApk():
	#先清空目标工程output目录下的apk
	srcapkpath = app_copy_path + "/output"
	files = os.listdir(srcapkpath)
	for f in files:
		srcfile = srcapkpath + '/' + f
		if( os.path.isfile(srcfile) and
			f.endswith(".apk") ):
			os.remove(srcfile)
	
	#打包生成apk
	print("begin to createApk...")
	buildcmd = "ant -buildfile " + app_copy_path + "/build.xml deploy 2>>&1 1>>compilelog.txt" 
	os.system(buildcmd)
	print("finish createApk!")

	
#把生成的apk文件放到当前目录的output目录下(最终apk名字模板：huawei_popfarm_v6_four.apk)
def copyApkToOutput(channelname):
	outputdir = "./output/"
	if(False == os.path.exists(outputdir)):
		os.makedirs(outputdir)
	
	srcapkpath = app_copy_path + "/output"
	files = os.listdir(srcapkpath)
	
	for f in files:
		srcfile = srcapkpath + '/' + f
		desfile = outputdir + channelname + "_" + f 
		if( os.path.isfile(srcfile) and
			f.endswith(".apk") ):
			shutil.copyfile(srcfile,desfile)

#进行准备工作
def getReady():
	initConfig()
	createOutputDir()
	GenCustomRules.generateMulCustomRulesXMLByProjectClasspath(app_copy_path,"project.properties")
	copyCustomRulesFiles()
	copyConfigFiles()
	initAllBuildXML()


if __name__=="__main__":
	getReady()
	antCreateApk()
	copyApkToOutput("test")

